package dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import bean.Permission;
import bean.User;
import utils.DaoUtil;

public class PermissionDao {
	
	public Permission queryRootPermission(){
		String sql = "select * from permissions where pid=0";
		return DaoUtil.queryBean(sql, Permission.class);
	}

	
	public List<Permission> queryChildPermissions(Integer pid){
		String sql = "select * from permissions where pid=?";
		return DaoUtil.queryBeanList(sql, Permission.class, pid);
	}

	
	public List<Permission> queryAll(){
		String sql = "select * from permissions";
		return DaoUtil.queryBeanList(sql, Permission.class);
	}

	public void insertPermission(Permission permission){
		String sql = "insert into permissions(name,url,pid) values(?,?,?)";
		DaoUtil.insert(sql, permission.getName(),permission.getUrl(),permission.getPid());
	}
	
	public Permission queryById(Integer id){
		String sql = "select * from permissions where id = ?";
		return DaoUtil.queryBean(sql, Permission.class, id);
	}

	public void updatePermission(Permission permission){
		String sql = "update permissions set name =?, url = ? where id =?";
		DaoUtil.update(sql, permission.getName(),permission.getUrl(),permission.getId());
	}

	public void deletePermission(Permission permission){
		String sql = "delete from t_permission where id =?";
		DaoUtil.delete(sql, permission.getId());
	}

	public List<Integer> queryPermissionidsByRoleid(Integer roleid){
		String sql = "select permissionid from role_permission where roleid = ?";
		List<Map<String,Object>> list = DaoUtil.queryMapList(sql, roleid);
		List<Integer> retList = new ArrayList<Integer>();
		if(list!=null){
			for(Map<String,Object> map:list){
				retList.add((Integer)map.get("permissionid"));
			}
		}
		return retList;
	}

	public List<Permission> queryPermissionsByUser(User dbUser){
		String sql = "select * from permissions where "
				+ "id in (select permissionid from role_permission where "
				+ "roleid in (select roleid from user_role where "
				+ "userid = ?))";
		return DaoUtil.queryBeanList(sql, Permission.class, dbUser.getId());
	}

}
